package com.wufun.overseas.main.activity;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.ContentUris;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.view.View;
import android.widget.TextView;

import com.wufun.baselibrary.download.CommonDownloadTask;
import com.wufun.baselibrary.download.UtilsMy;
import com.wufun.baselibrary.download.Xzip;
import com.wufun.baselibrary.utils.FileUtils;
import com.wufun.baselibrary.utils.LogUtils;
import com.wufun.baselibrary.widgets.NoSwipeViewPager;
import com.wufun.overseas.R;
import com.wufun.overseas.adapters.MyFragmentAdapter;
import com.wufun.overseas.common.TabTypeInterface;
import com.wufun.overseas.main.base.MyActivity;
import com.wufun.overseas.main.base.MyApplication;
import com.wufun.overseas.main.base.MyFragment;
import com.wufun.overseas.main.fragment.PlayMainItemFragment;
import com.wufun.overseas.models.db.DownLoadModel;
import com.wufun.overseas.models.event.DownloadResultEvent;
import com.wufun.overseas.tools.CheckPathTools;
import com.wufun.overseas.tools.DownloadManager;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.io.IOException;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import ru.bartwell.exfilepicker.ExFilePicker;
import ru.bartwell.exfilepicker.data.ExFilePickerResult;

/**
 * Created by tangbl on 2017/11/30 0030.
 */

public class PlayMainActivtiy extends MyActivity {

    @Bind(R.id.release_tab_layout)
    TabLayout releaseTabLayout;
    @Bind(R.id.release_viewpager)
    NoSwipeViewPager releaseViewpager;
    @Bind(R.id.part_search_tx)
    TextView partSearchTx;

    private Fragment fragment;
    private MyFragmentAdapter adapter;
    private final int[] typeId = {TabTypeInterface.TYPE_ALL
            , TabTypeInterface.TYPE_ACTION, TabTypeInterface.TYPE_FIGHT
            , TabTypeInterface.TYPE_SHOOTING, TabTypeInterface.TYPE_LOCAL};
    private final String[] titles = {"All", "ACT", "FTG", "STG", "Local"};

    public EventBus eventBus;

    private static final int EX_FILE_PICKER_RESULT = 9;

    private String appFlag;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_playmain);
        ButterKnife.bind(this);
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    public void initWidget(View... v) {
        super.initWidget(v);
        setBarTitleTx(getString(R.string.play_title_str));
        appFlag = getResources().getString(R.string.app_flag);
        setBarRightIv(R.mipmap.ic_grey_cross).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
//                intent.setType("*/*");//设置类型，我这里是任意类型，任意后缀的可以这样写。
//                intent.addCategory(Intent.CATEGORY_OPENABLE);
//                try {
//                    startActivityForResult(intent, 1);
//                } catch (Exception e) {
//                    showToast(getResources().getString(R.string.notfind_app_error));
//                }

                ExFilePicker exFilePicker = new ExFilePicker();
                exFilePicker.setCanChooseOnlyOneItem(true);//单选
                if (appFlag.equals("APP_PSP") || appFlag.equals("APP_DC"))
                    exFilePicker.setChoiceType(ExFilePicker.ChoiceType.DIRECTORIES);//只选择文件夹
                else
                    exFilePicker.setChoiceType(ExFilePicker.ChoiceType.FILES);//只选择文件
                exFilePicker.setNewFolderButtonDisabled(true) ;//不能新建文件
                exFilePicker.setSortButtonDisabled(true) ;//不显示排序按钮
                exFilePicker.setQuitButtonEnabled(true) ;//显示退出按钮
                exFilePicker.setUseFirstItemAsUpEnabled(true) ;//顶部返回上一层目录item
                exFilePicker.start(mAty, EX_FILE_PICKER_RESULT);
            }
        });

        partSearchTx.setText(getResources().getString(R.string.toast_search_str));

        eventBus = new EventBus();

        adapter = new MyFragmentAdapter(getSupportFragmentManager());
        for (int i = 0; i < titles.length; i++) {
            Fragment temp = new PlayMainItemFragment();
            Bundle bundle = new Bundle();
            bundle.putInt("typeId", typeId[i]);
            temp.setArguments(bundle);
            adapter.addFragment(temp, titles[i]);
        }
        releaseViewpager.setPagingEnabled(true);//是否支持手势滑动
        releaseViewpager.setOffscreenPageLimit(titles.length);
        releaseViewpager.setAdapter(adapter);
        releaseTabLayout.setupWithViewPager(releaseViewpager);
    }

    @Override
    public void onUserEvent(DownloadResultEvent eventData) {
        super.onUserEvent(eventData);
        for (int i = 0; i < adapter.getCount(); i++) {
            ((MyFragment) adapter.getItem(i)).fragmentEvent(eventData);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    private String startDirectory;
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == Activity.RESULT_OK) {
            if (requestCode == EX_FILE_PICKER_RESULT) {
                ExFilePickerResult result = ExFilePickerResult.getFromIntent(data);
                if (result != null && result.getCount() > 0) {
                    // Here is object contains selected files names and path
                    String path = result.getPath();
                    List<String> names = result.getNames();
                    for (int i = 0; i < names.size(); i++) {
                        File f = new File(path, names.get(i));
                        try {
                            Uri uri = Uri.fromFile(f); //这里获取了真实可用的文件资源

//                            if (Build.VERSION.SDK_INT > Build.VERSION_CODES.KITKAT) {//4.4以后
                                startDirectory = CheckPathTools.getPath(this, uri);
//                            } else {//4.4以下下系统调用方法
//                                startDirectory = CheckPathTools.getRealPathFromURI(mContext, uri);
//                            }

                            LogUtils.e(">>>>>>>>>>>>>startDirectory:"+startDirectory);
                            copyFile(startDirectory);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }
    }

    private String fromPath;
    private String zipName;
    private String fileName;
    private long zipSize;
    private String filedir = MyApplication.getMyApplication().getAppRootPath();

    private void copyFile(final String path) {
        LogUtils.e(">>>>path:" + path);
        fromPath = path;
        if (path != null && !path.isEmpty()) {
            zipName = path.substring(path.lastIndexOf("/") + 1);
            if (appFlag.equals("APP_PSP") || appFlag.equals("APP_DC")){
                fileName = zipName;
                showLoading(mContext.getResources().getString(R.string.dialog_zip_ing_content), true);
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        LogUtils.e(">>>>path:" + path);
                        File f = new File(path);
                        zipSize = FileUtils.getFolderSize(f);
                        LogUtils.e(">>>>filedirtwo:" + filedir);
                        File tempfile = new File(filedir);
                        if (!tempfile.exists()) {
                            tempfile.mkdirs();
                        }
                        boolean bs = FileUtils.copyFolderWithSelf(path, filedir);
                        if (bs) {
                            Message msg = new Message();
                            msg.what = 1;
                            mhandler.sendMessage(msg);
                        } else {
                            Message msg = new Message();
                            msg.what = 2;
                            mhandler.sendMessage(msg);
                        }
                    }
                }).start();
            } else {
                final String suffix = path.substring(path.lastIndexOf(".")+1);
                fileName = zipName.replace("."+suffix, "");
                showLoading(mContext.getResources().getString(R.string.dialog_zip_ing_content), true);
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        LogUtils.e(">>>>path:" + path);
                        LogUtils.e(">>>>filedir:" + filedir);
                        File f = new File(path);
                        zipSize = f.length();
                        File tempfile = new File(filedir+fileName+"/");
                        if (!tempfile.exists()) {
                            tempfile.mkdirs();
                        }
                        boolean bs = FileUtils.copyFile(path, filedir+fileName+"/"+fileName+"."+suffix);
                        if (bs) {
                            Message msg = new Message();
                            msg.what = 1;
                            mhandler.sendMessage(msg);
                        } else {
                            Message msg = new Message();
                            msg.what = 2;
                            mhandler.sendMessage(msg);
                        }
                    }
                }).start();
            }

//            String temp = path.substring(path.lastIndexOf("."));
//            LogUtils.e(">>>>zipName:" + temp);
//            if (temp.equals(".zip")) {
//                fileName = zipName.replace("zip", "");
//                LogUtils.e(">>>>fileName:" + fileName);
//                showLoading(mContext.getResources().getString(R.string.dialog_zip_ing_content), true);
//                new Thread(new Runnable() {
//                    @Override
//                    public void run() {
//                        LogUtils.e(">>>>path:" + path);
//                        LogUtils.e(">>>>filedir:" + filedir);
//                        File f = new File(path);
//                        zipSize = f.length();
//                        String temp = path.substring(path.lastIndexOf("/")+1);
//                        LogUtils.e(">>>>filedirtwo:" + filedir+temp.replace(".zip", "")+"/"+temp);
//                        File tempfile = new File(filedir+temp.replace(".zip", "")+"/");
//                        if (!tempfile.exists()) {
//                            tempfile.mkdirs();
//                        }
//                        boolean bs = FileUtils.copyFile(path, filedir+temp.replace(".zip", "")+"/"+temp);
//                        if (bs) {
//                            Message msg = new Message();
//                            msg.what = 1;
//                            mhandler.sendMessage(msg);
//                        } else {
//                            Message msg = new Message();
//                            msg.what = 2;
//                            mhandler.sendMessage(msg);
//                        }
////                        try {
////                            LogUtils.e(">>>>filedir:" + filedir);
////                            File f = new File(path);
////                            zipSize = f.length();
////                            boolean bs = Xzip.upZipFile(f, filedir);
////                            if (bs) {
////                                Message msg = new Message();
////                                msg.what = 1;
////                                mhandler.sendMessage(msg);
////                            } else {
////                                Message msg = new Message();
////                                msg.what = 2;
////                                mhandler.sendMessage(msg);
////                            }
////                        } catch (IOException e) {
////                            e.printStackTrace();
////                            LogUtils.e(">>>>:" + e.getMessage());
////                            Message msg = new Message();
////                            msg.what = 2;
////                            mhandler.sendMessage(msg);
////                        }
//                    }
//                }).start();
//            } else {
//                showToast(mContext.getResources().getString(R.string.toast_wran_str));
//            }
        } else {
            showToast(mContext.getResources().getString(R.string.toast_rom_fail_str));
        }
    }

    @SuppressLint("HandlerLeak")
    Handler mhandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            cancelLoading();
            switch (msg.what) {
                case 1:
                    addDownloadData();
                    onUserEvent(new DownloadResultEvent(CommonDownloadTask.STATUS_FINISH, fromPath, TabTypeInterface.TYPE_LOCAL));
//                    EventBus.getDefault().post(new DownloadResultEvent(CommonDownloadTask.STATUS_FINISH, fromPath, TabTypeInterface.TYPE_LOCAL));
                    break;
                case 2:
                    showToast(mContext.getResources().getString(R.string.toast_rom_fail_str));
                    break;
            }
        }
    };

    private void addDownloadData() {

        DownLoadModel temp = new DownLoadModel(
                fromPath,
                "-1",
                filedir,
                filedir + zipName.replace(".zip", ""),
                filedir + zipName,
                zipSize,
                UtilsMy.FormatFileSize(zipSize),
                TabTypeInterface.TYPE_LOCAL,
                CommonDownloadTask.STATUS_FINISH,
                0,
                zipName.replace(".zip", ""),
                zipName,
                "",
                "0",
                System.currentTimeMillis(),
                ""
        );

        DownloadManager mDownloadManager = DownloadManager.getInstance();

        if (!mDownloadManager.isExist(temp.getDownloadUrl()))
            mDownloadManager.insertDownload(temp);
    }

    @OnClick({R.id.layout_search_ll})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.layout_search_ll:
                startActivity(new Intent(mContext, PlaySearchActivity.class));
                break;
        }
    }
}
